/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wxy.ej.flow.modules.act.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.base.UserDetailsDto;
import com.wxy.ej.flow.modules.act.bean.NewModel;
import com.wxy.ej.flow.modules.act.dto.ModelDto;
import com.wxy.ej.flow.modules.act.dto.ModelEntityQuery;
import com.wxy.ej.flow.modules.act.dto.page.PageInfo;
import com.wxy.ej.flow.modules.act.dto.page.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.impl.persistence.entity.ModelEntityImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 模型管理类
 *
 * @author dgb
 */
@Slf4j
@RestController
@RequestMapping("/act/model")
public class ModelController {

    private final String MODEL_ID = "modelId";
    private final String MODEL_NAME = "name";
    private final String MODEL_DESCRIPTION = "description";
    private final String MODEL_REVISION = "revision";

    @Resource
    private RepositoryService repositoryService;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 获取所有模型
     *
     * @return
     */
    @PreAuthorize("hasAuthority('act:model:query')")
    @PostMapping("/s")
    public Result<PageInfo<Model>> search(@RequestBody ModelEntityQuery model, String userDetailsJson) {
        UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(userDetailsJson, "act:model:query");
        // 0：全部数据， 10：机构内部数据 ; 20: 个人；
        int dataLimitType = userDetailsDto.getDataLimitType();

        Integer pageNum = model.getPageNum();
        Integer pageSize = model.getPageSize();
        ModelQuery modelQuery = repositoryService.createModelQuery();
        if (StringUtils.isNotBlank(model.getName())) {
            modelQuery.modelNameLike("%" + model.getName() + "%");
        }
        if (StringUtils.isNotBlank(model.getKey())) {
            modelQuery.modelKey(model.getKey());
        }

        switch (dataLimitType) {
            case 10:
                modelQuery.modelTenantIdLike("%companyId="+userDetailsDto.getCompanyId()+";%");
                break;
            case 20:
                modelQuery.modelTenantIdLike("%userId="+userDetailsDto.getUserId()+";%");
                break;
        }

        modelQuery.orderByCreateTime().desc();
        long total = modelQuery.count();
        List<Model> models = modelQuery.listPage((pageNum-1)*pageSize, pageSize);
        List<ModelDto> modelDtoList = new ArrayList<>();
        for(Model model1: models) {
            ModelDto dto = new ModelDto();
            BeanUtils.copyProperties(model1, dto);
            modelDtoList.add(dto);
        }
        PageInfo<ModelDto> pageInfo = PageUtil.toPageInfo(modelDtoList);
        pageInfo.setTotal(total);
        return Result.builder(pageInfo);
    }

    /**
     * 保存模型
     *
     * @param newModel
     * @return
     */
    @PostMapping(value = "/create")
    public Result create(@RequestBody NewModel newModel, String userDetailsJson) {
        UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(userDetailsJson);

        ObjectNode modelNode = objectMapper.createObjectNode();
        modelNode.put(MODEL_NAME, newModel.getName());
        modelNode.put(MODEL_DESCRIPTION, newModel.getDesc());
        modelNode.put(MODEL_REVISION, "1");

        Model model = repositoryService.newModel();
        model.setName(newModel.getName());
        model.setKey(newModel.getKey());
        model.setCategory(newModel.getCategory());
        model.setMetaInfo(modelNode.toString());
        model.setTenantId("userId="+userDetailsDto.getUserId()+";userName="+userDetailsDto.getUserName()+";deptId="+userDetailsDto.getDeptId()+";deptName="+userDetailsDto.getDeptName()+";companyId="+userDetailsDto.getCompanyId()+";");

        repositoryService.saveModel(model);
        String id = model.getId();

        //完善ModelEditorSource
        ObjectNode editorNode = objectMapper.createObjectNode();
        editorNode.put("id", "canvas");
        editorNode.put("resourceId", "canvas");
        ObjectNode stencilSetNode = objectMapper.createObjectNode();
        stencilSetNode.put("namespace",
                "http://b3mn.org/stencilset/bpmn2.0#");
        editorNode.putPOJO("stencilset", stencilSetNode);
        repositoryService.addModelEditorSource(id, editorNode.toString().getBytes(StandardCharsets.UTF_8));
        // return RespData.ok(id);
        return Result.builder(id).success();
    }

    /**
     * 保存模型
     *
     * @param newModel
     * @return
     */
    @PostMapping(value = "/edit")
    public Result edit(@RequestBody NewModel newModel) {
        Model model = repositoryService.createModelQuery().modelId(newModel.getId()).singleResult();
        model.setName(newModel.getName());
        model.setKey(newModel.getKey());
        repositoryService.saveModel(model);
        return Result.builder();
    }

    /**
     * 根据Id查询模型
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Model> getById(@PathVariable("id") String id) {
        Model model = repositoryService.createModelQuery().modelId(id).singleResult();
        // return RespData.ok(model);
        return Result.builder(model).success();
    }

    @GetMapping("/{id}/xml")
    public Result<Model> getXmlById(@PathVariable("id") String id) {
        Model modelData = repositoryService.getModel(id);
        BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
        JsonNode editorNode = null;
        try {
            byte[] source = repositoryService.getModelEditorSource(modelData.getId());
            // String s = new String(source);
            // System.out.println("=======xmljson queryxml:" + s);
            editorNode = new ObjectMapper().readTree(source);
        } catch (IOException e) {
            e.printStackTrace();
        }
        BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
        BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
        byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel);

        String xml = new String(bpmnBytes);
        return Result.builder(xml).success();
    }

    /**
     * 保存流程定义数据(xml convert to json, save json finally)
     */
    @PostMapping(value = "/{modelId}/xml/save")
    public Result saveModelXml(@PathVariable String modelId,
                             @RequestBody ModelDto modelDto) {
        try {
            Model model = repositoryService.getModel(modelId);
            ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
            modelJson.put(MODEL_NAME, model.getName());
            modelJson.put(MODEL_DESCRIPTION, modelDto.getDescription());
            model.setMetaInfo(modelJson.toString());
            // model.setName(modelDto.getName());
            model.setVersion(model.getVersion() + 1);
            repositoryService.saveModel(model);

            // bpmn_xml convert to xmlStreamReader
            byte[] source = Objects.requireNonNull(modelDto.getBpmn_xml().getBytes(StandardCharsets.UTF_8));
            // String unescapeXml = StringUtils.unescapeHtml(xml);//因过滤处理XSS时会对<,>等字符转码，此处需将字符串还原
            InputStream in_nocode = new ByteArrayInputStream(source);
            XMLInputFactory xmlFactory  = XMLInputFactory.newInstance();
            XMLStreamReader xmlStreamReader = xmlFactory.createXMLStreamReader(in_nocode);
            // xmlStreamReader convert to bpmnModel
            BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
            BpmnModel bpmnModel = xmlConverter.convertToBpmnModel(xmlStreamReader);
            // bpmnModel convert to json
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            JsonNode jsonNode = jsonConverter.convertToJson(bpmnModel);
            byte[] modelEditorSource = new ObjectMapper().writeValueAsBytes(jsonNode);
            // String json = new String(modelEditorSource);
            // System.out.println("=======xmljson save json:" + json);
            // save bpmn josn (xml->json)
            repositoryService.addModelEditorSource(model.getId(), modelEditorSource);

            // save png
            InputStream svgStream = new ByteArrayInputStream(Objects.requireNonNull(modelDto.getSvg_xml().getBytes(StandardCharsets.UTF_8)));
            TranscoderInput input = new TranscoderInput(svgStream);
            PNGTranscoder transcoder = new PNGTranscoder();
            // Setup output
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            TranscoderOutput output = new TranscoderOutput(outStream);
            // Do the transformation
            transcoder.transcode(input, output);
            final byte[] result = outStream.toByteArray();
            repositoryService.addModelEditorSourceExtra(model.getId(), result);
            outStream.close();

            return Result.builder();
        } catch (Exception e) {
            log.error("Error saving model", e);
            return Result.builder().fault(e.getLocalizedMessage());
        }
    }


    /**
     * 获取流程定义json数据
     * @param modelId
     * @return
     */
    @GetMapping(value = "/{modelId}/json")
    public ObjectNode getEditorJson(@PathVariable String modelId) {
        ObjectNode modelNode = null;

        Model model = repositoryService.getModel(modelId);

        if (model != null) {
            try {
                if (StringUtils.isNotEmpty(model.getMetaInfo())) {
                    modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
                } else {
                    modelNode = objectMapper.createObjectNode();
                    modelNode.put(MODEL_NAME, model.getName());
                }
                modelNode.put(MODEL_ID, model.getId());
                byte[] modelEditorSource = repositoryService.getModelEditorSource(model.getId());
                ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(new String(modelEditorSource, StandardCharsets.UTF_8));
                modelNode.putPOJO("model", editorJsonNode);

            } catch (Exception e) {
                log.error("Error creating model JSON", e);
                throw new ActivitiException("Error creating model JSON", e);
            }
        }
        return modelNode;
    }

    /**
     * 保存流程定义数据
     */
    @PutMapping(value = "/{modelId}/save")
    public void saveModel(@PathVariable String modelId, @RequestParam("name") String name,
                          @RequestParam("json_xml") String json_xml,
                          @RequestParam("svg_xml") String svg_xml,
                          @RequestParam("description") String description) {
        try {

            Model model = repositoryService.getModel(modelId);

            ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());

            modelJson.put(MODEL_NAME, name);
            modelJson.put(MODEL_DESCRIPTION, description);
            model.setMetaInfo(modelJson.toString());
            model.setName(name);
            model.setVersion(model.getVersion() + 1);
            repositoryService.saveModel(model);

            repositoryService.addModelEditorSource(model.getId(), Objects.requireNonNull(json_xml.getBytes(StandardCharsets.UTF_8)));

            InputStream svgStream = new ByteArrayInputStream(Objects.requireNonNull(svg_xml.getBytes(StandardCharsets.UTF_8)));
            TranscoderInput input = new TranscoderInput(svgStream);

            PNGTranscoder transcoder = new PNGTranscoder();
            // Setup output
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            TranscoderOutput output = new TranscoderOutput(outStream);

            // Do the transformation
            transcoder.transcode(input, output);
            final byte[] result = outStream.toByteArray();
            repositoryService.addModelEditorSourceExtra(model.getId(), result);
            outStream.close();

        } catch (Exception e) {
            log.error("Error saving model", e);
            throw new ActivitiException("Error saving model", e);
        }
    }

    /**
     * 删除模型
     *
     * @param id
     * @return
     */
    /*@DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable("id") String id) {
        Model model = repositoryService.createModelQuery().modelId(id).singleResult();
        if (model == null) {
            // return RespData.failed().appendMsg("模型不存在").build();
            return Result.builder("模型不存在").fault();
        }
        repositoryService.deleteModel(id);
        // return RespData.sucess().build();
        return Result.builder().success();
    }*/
    @GetMapping("/{modelId}/delete")
    public Result<?> delete(@PathVariable("modelId") String id) {
        Model model = repositoryService.createModelQuery().modelId(id).singleResult();
        if (model == null) {
            // return RespData.failed().appendMsg("模型不存在").build();
            return Result.builder("模型不存在").fault();
        }
        repositoryService.deleteModel(id);
        // return RespData.sucess().build();
        return Result.builder().success();
    }

    /**
     * 部署模型
     *
     * @param modelId
     * @return
     */
    @GetMapping("/{modelId}/deployment")
    public Result<?> deploy(@PathVariable("modelId") String modelId) {

        // 获取模型
        Model modelData = repositoryService.getModel(modelId);

        if (modelData == null) {
            // return RespData.invalid().appendMsg("模型不存在").build();
            return Result.builder().fault("模型不存在");
        }

        byte[] bytes = repositoryService.getModelEditorSource(modelData.getId());

        if (bytes == null) {
            // return RespData.invalid().appendMsg("请先设计流程定义并成功保存，再进行部署").build();
            return Result.builder().fault("请先设计流程定义并成功保存，再进行部署");
        }

        JsonNode modelNode = null;
        try {
            modelNode = new ObjectMapper().readTree(bytes);
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            if (model.getProcesses().size() == 0) {
                //return RespData.invalid().appendMsg("流程定义不符要求，请至少设计一条主线流程").build();
                return Result.builder().fault("流程定义不符要求，请至少设计一条主线流程");
            }
            byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model);
            //发布流程
            String processName = modelData.getKey() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment()
                    .name(modelData.getName())
                    .key(modelData.getKey())
                    .category(modelData.getCategory())
                    .addString(processName, new String(bpmnBytes, StandardCharsets.UTF_8))
                    .enableDuplicateFiltering() // 在部署时会检测已部署的相同文件的最后一条记录，如果内容相同，则不会部署
                    .deploy();
            modelData.setDeploymentId(deployment.getId());
            repositoryService.saveModel(modelData);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //return RespData.sucess().build();
        return Result.builder().success();
    }
}
